package com.gitee.hermer.engine.jars.core.dubbo;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.engine.jars.core.context.IEngineAppContext;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;
import com.gitee.hermer.engine.jars.dependent.dsm.IEnginePropertiesAware;
import com.gitee.hermer.engine.jars.dependent.dubbo.config.DubboProperties;

@Component
public class EngineDubboApplicationRefreshBeanEvent extends UtilsContext implements ApplicationListener<ContextRefreshedEvent>,IEnginePropertiesAware<DubboProperties>{

	private DubboProperties properties;

	private AtomicBoolean isTest = new AtomicBoolean(false);


	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if(isTest.compareAndSet(false, true)){
			try{
				// 测试执行dubbo invoker
				DubboProtocol protocol = DubboProtocol.getDubboProtocol();
				Collection<Invoker<?>> invokers = protocol.getInvokers();
				String dubboApplicationRule = StringUtils.format(EngineConstant.PATTERN_DUBBO_APPLICATION, properties.getAppName());
				for (Invoker<?> invoker : invokers) {
					if(StringUtils.match(invoker.getUrl().toString(), dubboApplicationRule) && invoker.getInterface().getMethods().length > 0){
						invoker.invoke(new RpcInvocation(invoker.getInterface().getMethods()[0],new Object[]{}));
						break;
					}
				}
			}catch (Exception e) {

			}
		}
	}

	@Override
	@Autowired
	public void setProperties(DubboProperties properties) {
		this.properties = properties;
	}

}
